import store from "@/store";
import {commonApi} from "@/api";
import utils from "@/libs/utils";

let lastShowTime = 0
export default {
  showChaPingAD(params = {
    force: false
  }) {
    if(!store.getters.chapingAdId) {
      console.log('没设置插屏adid')
      params.onClose && params.onClose()
      return;
    }
    if (store.getters.haveVIP || store.getters.hideAD) {
      console.log('vip 免广告 showChaPingAD')
      params.onClose && params.onClose()
      return;
    }

    console.log('lastShowTime < store.getters.adChaping', store.getters.adChaping)
    if (!params.force && Date.now() - lastShowTime < store.getters.adChaping) {
      console.log('太频繁', Date.now() - lastShowTime, '间隔：', store.getters.adChaping)
      params.onError && params.onError({message: '太频繁'})
      return
    }
    lastShowTime = Date.now()
    const interstitialAd = uni.createInterstitialAd({
      adpid: store.getters.chapingAdId
    });
    if (!interstitialAd) {
      console.log('没有广告')
      params.onError && params.onError({message: '没广告'})
      return;
    }

    interstitialAd.onLoad(() => {
      console.log("插屏 广告加载成功");
      params.onLoad && params.onLoad()
      interstitialAd.show().then(() => {
        console.log('show then')
      });
    })

    interstitialAd.onClose(() => {
      console.log("插屏 广告关闭");
      commonApi.uploadAD(2)
      params.onClose && params.onClose()
    });
    interstitialAd.onError((err) => {
      console.log("插屏 广告加载失败");
      params.onError && params.onError(err)
    });
  },
  showJiliAd(params = {}) {
    if (store.getters.hideAD) {
      console.log('vip 免广告 showJiliAd')
      params.onClose && params.onClose()
      return;
    }
    const rewardedVideoAd = uni.createRewardedVideoAd({
      adpid: store.getters.jiliAdId,
      urlCallback: { // 服务器回调透传参数
        userId: store.getters.mine ? store.getters.mine.userId : '',
        extra: JSON.stringify({
          page: utils.getCurrentPage()
        })
      }
    })

    this._jiliSuccessFn = () => {
      this._jiliSuccessFn = null
      params.onLoad && params.onLoad()
      rewardedVideoAd.show().then(() => {
        console.log('show then ###########')
      });
    }
    uni.showLoading({
      title: ''
    })
    rewardedVideoAd.onLoad(() => {
      console.log('onLoad ###########')
      uni.hideLoading()

      this._jiliSuccessFn && this._jiliSuccessFn()
    })
    rewardedVideoAd.onError((err) => {
      console.log('onError ###########', err)
      uni.hideLoading()

      this._jiliSuccessFn = null
      params.onError && params.onError(err)
    })
    rewardedVideoAd.onClose(({isEnded}) => {
      uni.hideLoading()

      this._jiliSuccessFn = null
      commonApi.uploadAD(1)
      console.log('onclose ###########')
      params.onClose && params.onClose(isEnded)
    })
  }
}
